package com.atguigu.yygh.cmn.cfg.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.yygh.cmn.service.DictService;
import com.atguigu.yygh.hosp.model.cmn.Dict;
import com.atguigu.yygh.hosp.vo.cmn.DictEeVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @version 1.0
 * @Author: 许啸林
 * @Date: 2021/7/15 12:19
 * EasyExcel导入实体监听
 */
public class DictDataListener extends AnalysisEventListener<DictEeVo> {
    private DictService dictService;
    private final int  BATCH_COUNT = 3000;
    private static final Logger logger = LoggerFactory.getLogger(DictDataListener.class);
    private List<DictEeVo> batchList = new ArrayList<DictEeVo>();
    public DictDataListener(DictService dictService) {
        this.dictService = dictService;
    }

    /**
     * 读取单行数据回调方法
     * @param dictvo
     * @param analysisContext
     */
    @Override
    public void invoke(DictEeVo dictvo, AnalysisContext analysisContext) {
        batchList.add(dictvo);
        if(batchList.size() > BATCH_COUNT) {
            logger.info("easyExcel 读取数据达到默认值,进行数据库存储");
            saveData();
            batchList.clear();
        }
    }

    /**
     * 读取所有数据回到方法
     * 批量集合未达到默认值时保存数据
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }

    /**
     * 数据库批量添加
     */
    private void saveData() {
        logger.info("开始数据库存储");
        List<Dict> dictList = batchList.stream().map(dictVo -> {
            Dict dict = new Dict();
            BeanUtils.copyProperties(dictVo, dict);
            return dict;
        }).collect(Collectors.toList());
        dictService.saveBatch(dictList);
        logger.info("数据库存储条数: " + dictList.size() + " 条");
    }
}
